from BloodSpiderModel.DjangoResponseTool.response_dict import response_dict, get_page, get_first_error
from BloodSpiderAPI.apis.user import utils as user_utils
from django import forms
from BloodSpiderAPI import models

# 用户表单
class UserForm(forms.ModelForm):
    class Meta:
        model = models.User
        fields = "__all__"

# 接收用户系统提供的用户信息
def receive_user_info(request):
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)

    
    user_id = request.POST.get('uid')

    if user_id:
        user = models.User.objects.filter(uid=user_id).first()
        if user:
            user_response = user_utils.utils_model_to_dict(user, set_info_js_path=request.set_info_js_path)
            return response_dict(message="用户信息获取成功", code=0, data=user_response)
    form = UserForm(request.POST.dict())
    if not form.is_valid():
        return response_dict(data=get_first_error(form), code=1, message="参数错误")

    try:
        user = form.save(commit=False)
        # 手动设置id
        user.uid = user_id
        user.save()
        response = user_utils.utils_model_to_dict(user, set_info_js_path=request.set_info_js_path)
        return response_dict(data=response, message="用户创建成功")
    except Exception as e:
        return response_dict(message=f"创建失败: {str(e)}", code=1)
